import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_qr_reader/qrcode_reader_view.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/common/constants.dart';
import 'package:osc/ui/pages/user/user_profile.dart';
import 'package:osc/ui/widgets/button/pd_button.dart';
import 'package:osc/ui/widgets/web_scaffold.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/regex_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:permission_handler/permission_handler.dart';

class QrCodeScanPage extends StatefulWidget {
  @override
  _QrCodeScanPageState createState() => _QrCodeScanPageState();
}

class _QrCodeScanPageState extends State<QrCodeScanPage> with WidgetsBindingObserver{

  @override
  void initState() {
    super.initState();

    PermissionHandler().checkPermissionStatus(PermissionGroup.camera).then((value){
      if(value != PermissionStatus.granted){
        PermissionHandler().requestPermissions([PermissionGroup.camera]);
      }
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      qrViewKey.currentState.startScan();
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: QrcodeReaderView(key: qrViewKey, onScan: onScan),
    );
  }

  GlobalKey<QrcodeReaderViewState> qrViewKey = GlobalKey();

  Future onScan(String data) async {
    if(qrViewKey.currentState.isScan) {
      qrViewKey.currentState.startScan();
    }
    if(!StringUtil.isEmpty(data)){
      if(RegexUtil.isURL(data)) {
        if(data.startsWith(Constant.USER_QR_CODE_PREFIX_HTTPS) || data.startsWith(Constant.USER_QR_CODE_PREFIX_HTTP)) {
          int userId;
          String userIdStr;
          int startIndex = 0;
          if (data.startsWith(Constant.USER_QR_CODE_PREFIX_HTTPS)) {
            startIndex = Constant.USER_QR_CODE_PREFIX_HTTPS.length;
          } else if (data.startsWith(Constant.USER_QR_CODE_PREFIX_HTTP)) {
            startIndex = Constant.USER_QR_CODE_PREFIX_HTTP.length;
          } else {

          }
          userIdStr = data.substring(startIndex);
          userId = int.parse(userIdStr);
          jump2Page(UserProfile(userId: userId));
        } else {
          jump2Page(WebScaffold(title: "", url: data,));
        }
      } else {
        showResultDialog(data);
      }
    }
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

  showResultDialog(String data){
    showDialog(
      context: context,
      builder: (BuildContext context){
        return AlertDialog(
          content: Text(data),
          actions: <Widget>[
            PdButton(
              data: "复制",
              onTap: (){
                Clipboard.setData(ClipboardData(text: data));
                showTips("已复制到粘贴板");
                Navigator.pop(context);
              },
              borderColor: Colors.green,
              textStyle: MyTextStyle.GREEN_BUTTON,
            ),
            PdButton(
              data: "关闭",
              onTap: (){
                Navigator.pop(context);
              },
              borderColor: Colors.green,
              textStyle: MyTextStyle.GREEN_BUTTON,
            ),
          ],
        );
      }
    );
  }

  jump2Page(Widget page){
    Navigator.of(context).pop();
    NavigatorUtil.pushPage(context, page);
  }
}